const { Router } = require('express');
const logger = require('../utils/logger');
const Resp = require('../model/resp');
const { validator, ValidQueue } = require('../midwares/valider');
const Aftersale = require('../model/aftersale');
const ezutil = require('../utils/ezutil');
const Img = require('../model/img');

const router = Router();

/**
 * 变更状态
 */
router.put('/', 
  ValidQueue([
    validator.query('aid').exists().withMessage("未指定aid").trim().notEmpty().withMessage("aid不能为空"),
    validator.query('astate').exists().withMessage("未指定状态")
     .toInt().withMessage("不合法的状态")
     .custom(async (value)=>{
      console.log(value == 1)
      const states = [-1,1,2];
      if(!states.includes(value)) {
        throw new Error("不合法的状态");
      }
     })
  ]),
async (req, res, next)=>{
  const aid = req.query.aid;
  const record = await Aftersale.findByPk(aid);
  logger.debug(JSON.cycle(record));
  if(!record){
    res.json(Resp.fail("变更失败，记录不存在", -1, record)).end();
    return;
  }
  if (record.astate == -1) {
    return res.json(Resp.fail("变更失败，已取消", -2, {astate: record.astate})).end();
  }
  if (record.astate == 2) {
    return res.json(Resp.fail("变更失败，已解决", -3, {astate: record.astate})).end();
  }
  /**
   * @type {number}
   */
  const astate = req.query.astate;
  logger.debug(`astate: ${astate}`);
  logger.debug(`record.astate: ${record.astate}`);
  if (astate == 1 && record.astate == 1) {
    return res.json(Resp.fail("变更失败，已受理", -4, {astate: record.astate})).end();
  }
  record.update({
    astate: astate
  });
  await record.save();
  record.set('atime', ezutil.getDatetime(record.get('atime')));
  switch (astate) {
    case -1:
      return res.json(Resp.ok("成功取消", 1, {astate: record.astate})).end();
    case 1:
      return res.json(Resp.ok("成功受理", 2, {astate: record.astate})).end();
    case 2:
      return res.json(Resp.ok("解决确认", 3, {astate: record.astate})).end();
    default:
      break;
  }  
});

module.exports = router;
